package com.jrx.anytxn.transaction.job.autoPayment.step;

import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.entity.PrAutoPaymentTable;
import com.jrx.anytxn.param.mapper.ext.ExtPrAutoPaymentTableMapper;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.AmLoanAccountInfo;
import com.jrx.anytxn.transaction.entity.BtAutoPaymentList;
import com.jrx.anytxn.transaction.mapper.ext.ExtBtAutoPaymentListMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 第一次批扣处理
 *
 * @author : zhenghaopu
 * 2019/11/22
 */
@Service
public class AutoPaymentFirstInitStep2Processor implements ItemProcessor<AmLoanAccountInfo, BtAutoPaymentList> {

    private final Logger logger = LoggerFactory.getLogger(AutoPaymentFirstInitStep2Processor.class);

    @Autowired
    private ISegmentService segmentService;

    @Resource
    private ExtBtAutoPaymentListMapper extBtAutoPaymentListMapper;

    @Override
    public BtAutoPaymentList process(AmLoanAccountInfo item) throws Exception {

        Integer count =
                extBtAutoPaymentListMapper.selectByChannelAndCustomerForBatch(item.getCustomerId(),item.getChannel(),
                        item.getTenantId());
        //若已存在客户批扣数据 则返回
        if(count>0){
            return null;
        }
        BtAutoPaymentList autoPaymentList = new BtAutoPaymentList();
        try {
            autoPaymentList.setId(segmentService.getId(TransBizConstant.BT_AUTO_PAYMENT_LIST_ID));//主键
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }

        autoPaymentList.setChannel(item.getChannel());//渠道
        autoPaymentList.setTenantId(item.getTenantId());//租户id
        autoPaymentList.setOrganizationId(item.getOrganizationId());//机构
        autoPaymentList.setCustomerId(item.getCustomerId());//客户id
        autoPaymentList.setProductId("");
        autoPaymentList.setAutoPaymentType("");
        autoPaymentList.setFirstPaymentFlag(TransBizConstant.YES_FLAG);//是否首次批扣
        autoPaymentList.setUpdateBy(TransBizConstant.SYS_OPRATE);//创建人
        autoPaymentList.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);
        return autoPaymentList;
    }
}
